#region

using System;
using DomainModel.Domain.Model;
using DomainModel.Domain.Model.ServiceModel;
using EsbMonitor.Ninject;
using EsbMonitorMessages.Events;
using NServiceBus;

#endregion

namespace EsbMonitor.Handlers
{
    public class ServiceStartedEventHandler : IHandleMessages<IServiceStarted>
    {
        public IBus Bus { get; set; }

        public void Handle(IServiceStarted message)
        {
            var servicesRepository = KernelContainer.Get<IServicesRepository>();

            QueueInfo inputQueueInfo = new QueueInfo(message.ServiceInfo.InputQueue.QueueName);
            QueueInfo errorQueueInfo = message.ServiceInfo.ErrorQueue != null ? new QueueInfo(message.ServiceInfo.ErrorQueue.QueueName) : null;
            QueueInfo auditQueueInfo = message.ServiceInfo.AuditQueue != null ? new QueueInfo(message.ServiceInfo.AuditQueue.QueueName) : null;

            Service service = servicesRepository.Get(inputQueueInfo) ?? new Service(servicesRepository.NextServiceId())
                                                                                  {
                                                                                      CreateModifyInfo = {Created = DateTime.Now},
                                                                                      FirstSeen = message.EventTime
                                                                                  };
            service.Name = message.ServiceInfo.Name;
            service.Version = message.ServiceInfo.Version;
            service.Summary = message.ServiceInfo.Summary;
            service.LastStarted = service.LastAlive = message.EventTime;
            service.CreateModifyInfo.LastModified = DateTime.Now;
            service.InputQueue = inputQueueInfo;
            service.ErrorQueue = errorQueueInfo;
            service.AuditQueue = auditQueueInfo;
            



            //todo: usunac wszystkie MessageAssemblies i ServiceRoles, ktore maja EventTime < service.LastStarted

            servicesRepository.Store(service);
        }
    }
}